package com.whatech.mall.product.controller;

import com.whatech.mall.product.exception.ProductException;
import com.whatech.mall.product.model.dto.ProductDTO;
import com.whatech.mall.product.model.entity.Product;
import com.whatech.mall.product.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 商品Controller。
 */
@RestController
@RequestMapping("/product")
@Slf4j
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/query/{id}")
    public ProductDTO query(@PathVariable Long id) {
        log.info("call ProductController.query(), id = {}", id);
        // 假设当商品ID为“0”时，代表商品不存在
        if (id == 0) {
            return null;
        }
        // 模拟当商品ID为“999”时，请求异常
        if (id == 999) {
            throw new ProductException("product query error");
        }
        Product product = productService.findById(id);
        ProductDTO productDTO = new ProductDTO();
        BeanUtils.copyProperties(product, productDTO);
        return productDTO;
    }

}
